/**
 * 计算字符串的长度
 */

// export const getStrWidth = str => {
//     let canvas = document.createElement('canvas');
//     canvas.style.positon = 'ablsolute';
//     let ctx = canvas.getContext('2d');

//     function getCharSizeByCanvas(char, style = {}) {
//         let { fontSize = 14, fontFamily = '微软雅黑' } = style;
//         document.body.appendChild(canvas);
//         ctx.font = `${fontSize}px ${fontFamily}`;
//         document.body.removeChild(canvas);
//         let text = ctx.measureText(char); // TextMetrics object
//         ctx.fillText(char, 50, 50);
//         let result = {
//             height: fontSize,
//             width: text.width
//         };

//         return result;
//     }
//     return getCharSizeByCanvas(str).width;
// };

function measureText(attrs) {
    const context = document.createElement('canvas').getContext('2d');
    context.font = attrs.font;
    return context.measureText(attrs.text).width;
}
export function fittingString(str, maxWidth, font) {
    let text = str;
    let isTrim = false;
    let ellipsis = '…';
    let textWidth = maxWidth;
    const ellipsisWidth = measureText({ text: ellipsis, font });
    let currentWidth = measureText({ text, font });
    while (currentWidth > textWidth) {
        textWidth = maxWidth - ellipsisWidth;
        isTrim = true;
        text = text.substring(0, text.length - 1);
        currentWidth = measureText({ text, font });
    }

    return isTrim ? text + ellipsis : text;
}

/**
 * 计算字符串的长度
 */

export const getStrWidth = (str) => {
    let canvas = document.createElement('canvas');
    canvas.style.positon = 'ablsolute';
    let ctx = canvas.getContext('2d');

    function getCharSizeByCanvas(char, style = {}) {
        let { fontSize = 14, fontFamily = '微软雅黑' } = style;
        document.body.appendChild(canvas);
        ctx.font = `${fontSize}px ${fontFamily}`;
        document.body.removeChild(canvas);
        let text = ctx.measureText(char); // TextMetrics object
        ctx.fillText(char, 50, 50);
        let result = {
            height: fontSize,
            width: text.width,
        };

        return result;
    }
    return getCharSizeByCanvas(str).width;
};

export const suitableString = (str, maxWidth) => {
    let newStr = '';
    let w = 0;
    for (let i = 0; i < str.length; i++) {
        let strW = getStrWidth(str[i]);
        if (w < maxWidth) {
            w += strW;
            newStr += str[i];
        } else {
            return (newStr += '...');
        }
    }
    return newStr;
};
